package com.google.googlemarket.fragement;

import android.text.TextUtils;

import com.google.googlemarket.MyApp;
import com.google.googlemarket.utils.IOUtils;
import com.google.googlemarket.utils.Logger;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseBody;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Set;


/**
 * Created by Administrator on 2017/9/20.
 */
public class NetUtils {

    public static String getJson(String url, HashMap<String, String> params) {
        Logger.i("http","url:"+url+",params;"+params);
        String requestUrl = (params == null ? url : createRequestUrl(url, params));
        //先从本地加载数据，如果本地缓存为空就从网络上加载
        String json = requestFromLocal(requestUrl);
        if (TextUtils.isEmpty(json)){
            //从网络中加载数据
            json = requestFromNet(requestUrl);
        }
        return json;
    }

    /**
     * @param requestUrl 从本地获取包名.Cache缓存文件中获取数据
     * @return
     */
    private static String requestFromLocal(String requestUrl) {
        File cacheFile = getCacheFile(requestUrl);
        if (cacheFile.exists()) {
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new FileReader(cacheFile));
                String validTimeStr = reader.readLine();	// 读取缓存文件中的有准备时间
                long validTime = Long.valueOf(validTimeStr);

                // 判断缓存文件是否有效
                if (System.currentTimeMillis() < validTime) {
                    CharArrayWriter writer = new CharArrayWriter();
                    char[] buf = new char[2048];
                    int len;
                    while((len = reader.read(buf)) != -1) {
                        writer.write(buf, 0, len);
                    }
                    return writer.toString();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                IOUtils.close(reader);
            }
        }
        return null;
    }


    /**
     * 从网络中获取数据，并将数据缓存到本地
     * @param requestUrl
     * @return
     */
    private static String requestFromNet(String requestUrl) {
        OkHttpClient okHttpClient = new OkHttpClient();
        if (requestUrl!=null){
            Request request = new Request.Builder().url(requestUrl).build();
            Call call = okHttpClient.newCall(request);
            String requestJson = null;
            BufferedWriter bufferedWriter = null;
            try {
                Response execute = call.execute();
                requestJson = execute.body().string();
                Logger.i("http","requestJson:"+requestJson);
                File cacheFile = getCacheFile(requestUrl);
                bufferedWriter = new BufferedWriter(new FileWriter(cacheFile));
                long validTime = System.currentTimeMillis()+3*60*1000;
                bufferedWriter.write(validTime+"");
                bufferedWriter.newLine();
                bufferedWriter.write(requestJson);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                IOUtils.close(bufferedWriter);
            }
            return requestJson;
        }
        return null;
    }

    private static File getCacheFile(String requestUrl) {
        try {
            requestUrl = URLEncoder.encode(requestUrl, "UTF-8");
            File cacheFile = new File(MyApp.getmContext().getCacheDir(), requestUrl);
            return cacheFile;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 把指定的url和params拼接成一个请求地址
     * @param url
     * @param parmas
     * @return
     */
    private static String createRequestUrl(String url, HashMap<String, String> parmas) {
        Set<String> keySet = parmas.keySet();	// Set是无序的，无法排序，所以转换为ArrayList
        ArrayList<String> keys = new ArrayList<String>(keySet);
        Collections.sort(keys);	// 对集体排序

        // http://127.0.0.1:8090/home?index=0&age=47&name=zs
        // 把所有的参数拼接成index=0&age=47&name=zs
        StringBuffer sb = new StringBuffer();
        for (String key : keys) {
            sb.append("&").append(key).append("=").append(parmas.get(key));
        }
        // 上面for循环走完得到这样的字符串：&index=0&age=47&name=zs
        sb.deleteCharAt(0);// 删除第0位置的符号：&，得到：index=0&age=47&name=zs
        String requestUrl = url + "?" + sb.toString();
        return requestUrl;
    }
}
